<?php
declare (strict_types = 1);

namespace app\index\controller;
use app\BaseController;
use app\common\model\Field as FieldModel;
use app\common\model\Group as GroupModel;
use app\common\model\User as UserModel;
use think\Facade\Db;
use think\Facade\Env;
use think\Facade\View;
use think\helper\Str;

class User extends BaseController {
	/**
	 * 资料项管理
	 * @DateTime 2019-12-20
	 * @Author   BadmintonCode
	 */
	public function field() {
		if ($this->request->isAjax()) {
			if ($this->request->isGet()) {
				$fields = FieldModel::order('displayorder', 'asc')->select()->toArray();
				return doSuccess(['fields' => $fields, 'infomod' => $this->settings['infomod']]);
			} else {
				$post = $this->request->post();
				if ($post['delete']) {
					foreach ($post['delete'] as $key => $value) {
						$post['delete'][$key] = intval($value);
					}
					FieldModel::destroy($post['delete']);
				}
				$list = [];
				$insert = [];
				$maxId = FieldModel::max('field_id');
				foreach ($post['field_id'] as $key => $value) {
					if ($post['delete'] && in_array($value, $post['delete'])) {
						continue;
					}
					$key = intval($key);
					$update = [
						'displayorder' => $key,
						'title' => strip_tags(trim($post['title'][$key])),
						'setting' => strip_tags(trim($post['setting'][$key])),
						'type' => strip_tags(trim($post['type'][$key])),
						'defaultvalue' => strip_tags(trim($post['defaultvalue'][$key])),
						'available' => intval($post['available'][$key]),
						'required' => intval($post['required'][$key]),
						'mods' => strip_tags(trim($post['mods'][$key])),
						'tips' => strip_tags(trim($post['tips'][$key])),
					];
					if (is_numeric($value)) {
						$update['field_id'] = $value;
					}
					$list[] = $update;
				}
				$model = new FieldModel;
				$model->saveAll($list);
				$fields = FieldModel::order('displayorder', 'asc')->select()->toArray();
				//获取user表所有字段
				$field_ids = [];
				$userColumns = Db::getFields('user');
				foreach ($fields as $field) {
					$field_ids[] = 'field' . $field['field_id'];
					if ($userColumns['field' . $field['field_id']]) {
						continue; //字段已存在
					} else {
						//字段未存在，新增字段
						Db::execute("ALTER TABLE user ADD COLUMN field" . $field['field_id'] . " VARCHAR(128) DEFAULT '" . $field['defaultvalue'] . "'");
					}
				}
				foreach ($userColumns as $key => $value) {
					if (strstr($key, 'field') !== false && !in_array($key, $field_ids)) {
						//用户表存在，信息字段表不存在，删除用户表中该字段
						Db::execute("ALTER TABLE user DROP COLUMN " . $key);
					}
				}

				return doSuccess('success.save', ['fields' => $fields, 'infomod' => $this->settings['infomod']]);
			}
		}

		$this->title('资料项设置');
		$this->js('/static/libs/xm-select.js');
		return View::fetch();
	}
	/**
	 * 管理用户组
	 * @DateTime 2019-12-18
	 * @Author   BadmintonCode
	 */
	public function groups() {
		if ($this->request->isAjax()) {
			if ($this->request->isGet()) {
				$menus = \app\common\model\Menu::getMenus()->toArray();
				$groups = GroupModel::order('displayorder', 'asc')->select()->toArray();
				return doSuccess(['menus' => $menus, 'groups' => $groups]);
			} else {
				$post = $this->request->post();
				if ($post['delete']) {
					if (in_array('1', $post['delete'])) {
						return doReturn('systemDelete');
					}
					foreach ($post['delete'] as $key => $value) {
						$post['delete'][$key] = intval($value);
					}
					GroupModel::destroy($post['delete']);
				}
				$list = [];
				$insert = [];
				$maxGroup = GroupModel::max('group_id');
				foreach ($post['group_id'] as $key => $value) {
					$group_id = intval($value);
					if ($post['delete'] && in_array($group_id, $post['delete'])) {
						continue;
					}
					$key = intval($key);
					$update = [
						'group_id' => $group_id,
						'displayorder' => $key,
						'title' => strip_tags(trim($post['title'][$key])),
					];
					if ($group_id > $maxGroup) {
						unset($update['group_id']);
					}
					if ($group_id != 1) {
						$update['rules'] = strip_tags(trim($post['rules'][$key]));
					}
					$list[] = $update;
				}
				$model = new GroupModel;
				$model->saveAll($list);
				$menus = \app\common\model\Menu::getMenus()->toArray();
				$groups = GroupModel::order('displayorder', 'asc')->select()->toArray();
				return doSuccess('success.save', ['menus' => $menus, 'groups' => $groups]);
			}

		}
		$this->title('用户组');
		$this->js('/static/libs/xm-select.js');
		return View::fetch();
	}

	public function list() {
		if ($this->request->isAjax()) {
			if ($this->request->isPost()) {
				$want = $this->request->post('want');
				if ($want == 'init') {
					//获取列宽
					$infomods = explode("\n", $this->settings['infomod']);
					$fields = FieldModel::whereNotNull('mods')->where('mods', '<>', '')->order('displayorder', 'asc')->where('available', 1)->select()->toArray();
					$modFields = [];
					foreach ($infomods as $k => $v) {
						foreach ($fields as $key => $value) {
							if (strlen($value['mods']) == 0) {
								continue;
							}

							$mods = explode(',', $value['mods']);
							if (in_array($k, $mods)) {
								$modFields[$k][] = ['field' => 'field' . $value['field_id'], 'title' => $value['title'], 'type' => $value['type'], 'setting' => $value['setting']];
							}

						}
					}
					foreach ($infomods as $key => $value) {
						if (count($modFields[$key]) == 0) {
							unset($infomods[$key]);
						}
					}
					$infomods = array_values($infomods);
					$modFields = array_values($modFields);
					$groups = GroupModel::order('displayorder', 'asc')->column('title', 'group_id');
					return doSuccess(['infomods' => $infomods, 'modFields' => $modFields, 'groups' => $groups]);
				} elseif ($want == 'add') {
					$do = UserModel::register($this->request->post('email', '', 'trim,strip_tags'), $this->request->post('password', '', 'trim'), $this->request->post('status', '', 'intval'), $this->request->post('group_id', '', 'intval'), $this->request->post('addition', '', 'trim,strip_tags'));
					if (is_string($do)) {
						return doReturn($do);
					} else {
						return doSuccess('success.add');
					}
				} elseif ($want == 'field') {
					$field = $this->request->post('field', '', 'trim,strip_tags');
					if (!in_array($field, ['addition'])) {
						return doReturn('user.fieldReadonly');
					}
					$value = $this->request->post('value', '', 'trim,strip_tags');
					$user_id = $this->request->post('user_id', '', 'intval');
					UserModel::update([$field => $value], ['user_id' => $user_id]);
					return doSuccess('success.modify');
				} elseif (in_array($want, ['multiGroup', 'multiStatus', 'multiDelete'])) {
					//校验用户
					$users = $this->request->post('users');
					foreach ($users as $key => $value) {
						$value = intval($value);
						$item = UserModel::where('user_id', $value)->field('email,group_id')->find();
						//校验是否是站长和开启了允许管理员之间相互修改
						if ($item['group_id'] == 1 && Env::get('ALLOW_BUILDER') != true) {
							return doReturn('user.nopower', [], false, [$item['email']]);
						}
						$users[$key] = $value;
					}
					if ($want == 'multiGroup') {
						//批量修改用户组
						$group_id = $this->request->post('group_id', '', 'intval');
						if (!Db::name('group')->where('group_id', $group_id)->count()) {
							return doReturn('group.notExist');
						}

						UserModel::whereIn('user_id', implode(',', $users))->update(['group_id' => $group_id]);
						return doSuccess('success.modify');
					} elseif ($want == 'multiStatus') {
						//批量修改状态
						$status = $this->request->post('status', '', 'intval');
						if ($status != 0) {
							$status = 1;
						}

						UserModel::whereIn('user_id', implode(',', $users))->update(['status' => $status]);
						return doSuccess('success.modify');
					} elseif ($want == 'multiDelete') {
						//批量修改状态

						UserModel::destroy($users);
						return doSuccess('success.delete');
					}
				} elseif (in_array($want, ['login', 'edit', 'password'])) {
					$user_id = $this->request->post('user_id', '', 'intval');
					$user = UserModel::find($user_id);
					if ($user->group_id == 1 && Env::get('ALLOW_BUILDER') != true) {
						return doReturn('user.nopower', [], false, [$user['email']]);
					}
					if ($want == 'login') {
						\think\Facade\Session::set('user', $user);
						return doSuccess(['pReload' => true]);
					} elseif ($want == 'password') {
						$password = $this->request->post('password', '', 'trim');
						if (strlen($password) < 6) {
							return doReturn('password.short');
						}

						$user->salt = Str::random($length = 16);
						$user->password = salt_password($user->salt, $password);
						$user->save();
						return doSuccess('success.modify');
					}

				}
			}
			$model = new UserModel;
			$model->where('user_id', '>', 0);
			$count = $model->count();
			$fields = ['user_id', 'create_time', 'update_time'];
			$orders = ['desc', 'asc'];
			$field = $this->request->get('field', $fields[0], 'trim,addslashes');
			if (!in_array($field, $fields)) {
				$field = $fields[0];
			}
			$order = $this->request->get('order', $orders[0], 'trim,addslashes');
			if (!in_array($order, $orders)) {
				$order = $orders[0];
			}
			$list = $model
				->order($field, $order)
				->page($this->request->get('page', 1, 'intval'), min($this->request->get('limit', 10, 'intval'), 100))
				->select()
				->toArray();
			return json(['code' => 200, 'count' => $count, 'data' => $list]);
		}
		$this->title('用户管理');
		$this->js('/static/libs/xm-select.js');
		return View::fetch();
	}
}
